import type { HttpRequestConfig, HttpTask } from '../../../luch-request'

function sortParams(params: { [x: string]: any }): Record<string, any> {
  return Object.keys(params)
    .sort()
    .reduce((sorted: Record<string, any>, key) => {
      sorted[key] = params[key]
      return sorted
    }, {} as Record<string, any>)
}

function serializeParams(params: Record<string, any>): string {
  return Object.entries(params)
    .map(([key, value]) => `${key}=${encodeURIComponent(JSON.stringify(value))}`)
    .join('&')
}

/**
 * 生成请求唯一标识
 * @param {*} config
 * @param {*} uid prefix uid
 * @param {*} defaultCacheMode memory临时缓存 ,lasting永久缓存
 */
function uuid(config = {} as HttpRequestConfig<HttpTask>, uid = '', defaultCacheMode: 'memory' | 'lasting' = 'memory'): string {
  const { method, baseURL, url, params = {}, data = {}, custom = {} } = config

  const cacheMode = custom.cacheMode || ''
  uid = uid || ''
  const sortedParams = sortParams({ ...params, ...data })
  const serial = serializeParams(sortedParams)
  const cacheKey = method + (baseURL || '') + url + serial + uid

  if (!cacheMode) return defaultCacheMode === 'memory' ? `_${cacheKey}` : cacheKey
  if (cacheMode === 'lasting') return cacheKey
  if (cacheMode === 'memory') return `_${cacheKey}`
  return ''
}

export default uuid
